package mianyang.zhangsan.com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import mianyang.zhangsan.com.pojo.LeaveWord;
import mianyang.zhangsan.com.pojo.LeaveWordCustom;
import mianyang.zhangsan.com.pojo.User;
import mianyang.zhangsan.com.service.LeaveWordService;
import mianyang.zhangsan.com.service.UserService;
import mianyang.zhangsan.com.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/leave")
public class LeaveController {
    @Autowired
    private LeaveWordService leaveWordService;
    @Autowired
    private UserService userService;

    /**
     * 前台展示所有留言信息
     * @param pageNo
     * @param model
     * @return
     */
    @RequestMapping("/frontList")
    public String frontList(@RequestParam("pageNo")int pageNo, Model model){
        Page<LeaveWord> leaveWordPage = leaveWordService.queryPage(pageNo);
        List<LeaveWordCustom> leaveWordList = new ArrayList<>();
        List<User> users = new ArrayList<>();
        for (LeaveWord leaveWord:leaveWordPage.getRecords()){
            User user = userService.queryUserInfo(leaveWord.getUsername());
            users.add(user);
            LeaveWordCustom leaveWordCustom = new LeaveWordCustom();
            leaveWordCustom.setUser(user);
            leaveWordList.add(leaveWordCustom);
        }
        model.addAttribute("users", users);
        model.addAttribute("leaveWordList", leaveWordList);
        model.addAttribute("pages", leaveWordPage.getPages());
        leaveWordPage.setRecords(null);
        model.addAttribute("page", leaveWordPage);
        return "leave/leaveword_front_result";
    }

    /**
     * 后台跳转到留言页面
     * @return
     */
    @RequestMapping("/toAdd")
    public String leaveToAdd(){
        return "leave/leaveword_add";
    }

    /**
     * 后台跳转到留言展示页面
     * @return
     */
    @RequestMapping("/query")
    public String query(){
        return "leave/leaveword_query_result";
    }

    /**
     * 后台添加留言
     * @param leaveWord
     * @return
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public String leaveAdd(LeaveWord leaveWord){
        if (leaveWord != null){
            leaveWordService.leaveAdd(leaveWord);
            return "{\"success\":true}";
        }
        return "{\"success\":false}";
    }

    /**
     * 后台查询留言信息
     * @param page
     * @param rows
     * @param leaveWord
     * @return
     */
    @RequestMapping(value = "/list", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String leaveList(int page, int rows, LeaveWord leaveWord){
        System.out.println(leaveWord);
        Page<LeaveWord> leaveWordPage = leaveWordService.queryPageWrapper(page, rows, leaveWord);
        JSONObject response = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        response.put("total", leaveWordPage.getPages());
        for (LeaveWord item : leaveWordPage.getRecords()){
            Object o = JSON.toJSON(item);
            jsonArray.add(o);
        }
        response.put("rows", jsonArray);
        return response.toString();
    }

    /**
     * 后台更新留言
     * @param leaveWordId
     * @param leaveWord
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(int leaveWordId, LeaveWord leaveWord){
        leaveWordService.update(leaveWordId, leaveWord);
        return "{\"success\": true}";
    }

    /**
     * 删除留言
     * @param leaveWordIds
     * @return
     */
    @RequestMapping("/deletes")
    @ResponseBody
    public String deletes(String leaveWordIds){
        leaveWordService.deletes(leaveWordIds);
        return "{\"success\": true}";
    }

    /**
     * 后台导出留言信息
     * @param leaveWord
     * @param response
     */
    @RequestMapping("/outToExcel")
    public void toExcel(LeaveWord leaveWord, HttpServletResponse response){
        List<LeaveWord> leaveWords = leaveWordService.queryListByWrapper(leaveWord);
        String[] headers = {"序号", "标题", "内容", "留言人", "留言时间", "回复内容", "回复时间"};
        String title = "留言表";
        List<String[]> contents = new ArrayList<>();
        for (LeaveWord item : leaveWords){
            contents.add(new String[]{item.getLeaveWordId().toString(), item.getTitle(), item.getContent(),item.getUsername(),item.getTime(),item.getReply(),item.getReplyTime()});
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setHeader("Content-disposition","attachment; filename="+"leaveWord.xls");//filename是下载的xls的名，建议最好用英文
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma","No-cache");//设置头
            response.setHeader("Cache-Control","no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头
            ExcelUtils.exportExcel(title, headers, contents, out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
